import dayjs, { WEEKDAY } from '@/plugins/dayjs'
import { useCreateContentStore } from '../../store'
import { useBasicInfoStore } from './store'
import { store as addMtSelectedStore } from '@/components/AddMt/blocks/selected/store'
import { useGlobalStore } from '@/store/global'
import {
	fetchCheckRoomBookOrLocked,
	fetchCheckRoomBookOrLockedCheck,
	fetchDeleteBookedMeetingRoom,
	fetchDeleteMeetingRoom,
	fetchGetMeetingRoom,
	fetchLoadMeetingRoom,
	fetchLoadRegularMeetingRoom,
	fetchLockMeetingRoom,
	fetchMeetingRoomLockExist,
	fetchUnLockMeetingRoom,
} from '@/api/create'
import { FetchLoadMeetingRoom, FetchLockMeetingRoom, FetchMeetingRoomParams } from '@/api/create/interface'
import { Message } from '@kedacom/react-next'
import { t } from 'i18next'
import Alert, { confirmModal } from '@/components/Alert'
import { ICriteria } from './interface'
import { removeAllRooms } from '../user/store.combine'

/** 删除会议室信息 */
export function removeRoomData() {
	useBasicInfoStore.setState({ roomData: null })
	useCreateContentStore.setState({ meetingFormKey: '' })
	removeAllRooms()
	addMtSelectedStore.getState().delAllSelectedRooms()
}

/** 校验是否会议室冲突
 * 修切换会议类型（视频会议、非视频会议），修改日期、开始时间、时长小时、时长分钟，都会调用此函数校验会议室是否可用
 * data false-例会或者有冲突会议 true-无冲突会议室
 */
export function checkAndUpdateExistRoomBookedOrLocked(
	callBack: ({ success, data }: { success: boolean; data: boolean }) => void
) {
	const { day, startTime, hour, minute, repeat, roomData } = useBasicInfoStore.getState()
	//获取会议室信息
	if (
		!roomData ||
		roomData.success_num === 0 ||
		!(useGlobalStore.getState().serverInfo?.enable_room && useGlobalStore.getState().user?.enable_kis)
	) {
		callBack({ data: true, success: true })
		return
	}
	let _startTime = day + ' ' + startTime + ':00'
	let _endTime = dayjs(_startTime)
		.add(hour * 60 + minute, 'minute')
		.format('YYYY-MM-DD HH:mm:ss')

	if (!repeat) {
		fetchCheckRoomBookOrLockedCheck({
			meeting_moid: useCreateContentStore.getState().meetingMoid,
			meeting_form_key: useCreateContentStore.getState().meetingFormKey,
			start_time: _startTime,
			end_time: _endTime,
			meeting_type: 1,
		}).then((res) => callBack({ data: res.success && res.data ? true : false, success: !!res.success }))
	} else {
		callBack({ data: false, success: true })
	}
}

/** 编辑会议时调用room_booked_or_locked_check返回true会取消原有的会议室锁定，需手动锁定 */
export function lockRoomAfterCheck() {
	const { roomData, day, startTime, hour, minute } = useBasicInfoStore.getState()
	if (!(useGlobalStore.getState().serverInfo?.enable_room && useGlobalStore.getState().user?.enable_kis) || !roomData)
		return
	let meetingRooms = roomData.data[0].meeting_rooms //非例会的推荐会议室都在一个data中
	if (!useCreateContentStore.getState().meetingFormKey && meetingRooms) {
		//编辑会议室meetingFormKey没有，需要手动锁定
		let _startTime = day + ' ' + startTime + ':00'
		let _endTime = dayjs(_startTime)
			.add(hour * 60 + minute, 'minute')
			.format('YYYY-MM-DD HH:mm:ss')
		let ajaxList: Promise<FetchLockMeetingRoom>[] = []
		meetingRooms.forEach((room) => {
			if (!room.id) return
			//根据roomid去批量获取区域信息
			let promise: Promise<FetchLockMeetingRoom> = new Promise((resolve, reject) => {
				fetchGetMeetingRoom(room.id).then((res) => {
					resolve({
						start_time: _startTime,
						end_time: _endTime,
						region_id: res?.region ?? '',
						region_name: room.region_name ?? '',
						meeting_room_id: room.id ?? '',
						meeting_room_name: room.name ?? '',
						virtual_available: 1,
						meeting_form_key: '',
					})
				})
			})
			ajaxList.push(promise)
		})
		Promise.all(ajaxList).then((res) => {
			fetchLockMeetingRoom(res).then((data) => {
				useCreateContentStore.setState({ meetingFormKey: data })
			})
		})
	}
}
/** 清除锁定会议室 */
export function clearCheckedMeetingRooms(
	yesCallback: () => void,
	noCallBack: () => void,
	msg: React.ReactNode,
	//搜索会议室弹窗关闭不判断roomData
	withoutRoomData?: boolean
) {
	const { roomData } = useBasicInfoStore.getState()
	if (
		useGlobalStore.getState().serverInfo?.enable_room &&
		useGlobalStore.getState().user?.enable_kis &&
		(withoutRoomData || (roomData && roomData.success_num !== 0))
	) {
		checkExistRoomBookedOrLocked((flag) => {
			if (flag) {
				confirmModal({
					msg: msg,
					onOk: () => {
						unLockMeetingRoom(() => {
							removeRoomData()
							yesCallback()
						})
					},
					onCancel: () => {
						noCallBack()
					},
				})
			} else {
				yesCallback()
			}
		})
	} else {
		yesCallback()
	}
}
/**查询是否有锁定和预定的会议室 */
export function checkExistRoomBookedOrLocked(cb: (flag: boolean) => void) {
	let m = Message.loading(t('正在查询是否已占用会议室，请稍候……'))
	fetchCheckRoomBookOrLocked({ id: useCreateContentStore.getState().meetingMoid })
		.then((res) => {
			if (res.success) {
				cb(!!res.data)
			} else {
				Alert(t('检测是否已锁定会议室出错'))
			}
			m.hide()
		})
		.catch(() => {
			m.hide()
		})
}

/**解锁锁定的会议室  notDeleteBookedMeetingRoom-不触发取消预定会议室接口*/
export function unLockMeetingRoom(cb: () => void, notDeleteBookedMeetingRoom?: boolean) {
	let m = Message.loading(t('正在释放占用的会议室，请稍候……'))
	let meetingMoid = useCreateContentStore.getState().meetingMoid
	fetchUnLockMeetingRoom({ meeting_form_key: useCreateContentStore.getState().meetingFormKey })
		.then((res) => {
			if (res.success) {
				if (notDeleteBookedMeetingRoom) {
					cb()
				} else {
					deleteBookedMeetingRoom(cb)
				}
				if (meetingMoid) {
					//通知后台
					fetchDeleteMeetingRoom(meetingMoid)
				}
			} else {
				Alert(t('释放锁定的会议室失败'))
			}
			m.hide()
		})
		.catch(() => {
			m.hide()
		})
}

/**删除已经预定的会议室 */
export function deleteBookedMeetingRoom(cb: () => void) {
	let meetingMoid = useCreateContentStore.getState().meetingMoid
	fetchDeleteBookedMeetingRoom({ meeting_moid: meetingMoid }).then((res) => {
		if (res.success) {
			cb()
		}
	})
}

/**推荐会议室 */
export function loadMeetingRooms(criteriaList: ICriteria[], cb: (data: FetchLoadMeetingRoom) => void) {
	const { repeat, day, hour, minute, startTime, meetingFormular } = useBasicInfoStore.getState()
	let m = Message.loading(t('正在加载符合条件的会议室，请稍候……'))

	const successFn = (data: FetchLoadMeetingRoom) => {
		m.hide()
		//更新搜索会议规则
		useBasicInfoStore.setState({
			meetingCriteriaList: criteriaList.map((item) => ({
				region_name: item.regionName,
				device_ids: item.deviceIds,
				num: item.num,
				region_id: item.regionId,
				up_seating: item.upSeating,
				down_seating: item.downSeating,
				meeting_room_id: item.meetingRoomId,
			})),
		})
		useCreateContentStore.setState({ meetingFormKey: data.data[0].meeting_form_key ?? '' })
		cb(data)
	}
	let data: FetchMeetingRoomParams[] = criteriaList.map((item) => ({
		num: item.num,
		day: day,
		duration: hour * 60 + minute,
		region_id: item.regionId,
		device_ids: item.deviceIds,
		person_num_lower_limit: item.downSeating === 0 ? '' : item.downSeating.toString(),
		person_num_upper_limit: item.upSeating === 0 ? '' : item.upSeating.toString(),
		meeting_room_id: item.meetingRoomId,
		region_name: item.regionName,
		start_time: startTime,
		end_time: '21:00',
		meeting_moid: useCreateContentStore.getState().meetingMoid,
	}))

	if (repeat) {
		let param = {
			search_meeting_room_by_video: data,
			repeat: {
				frequency: 1,
				frequency_label: t('每周'),
				week_days: meetingFormular?.weekDays ?? '',
				week_day_labels:
					meetingFormular?.weekDays
						.split(',')
						.map((i) => WEEKDAY[Number(i)])
						.join(',') ?? '',
				end_date: meetingFormular?.endTime ?? '',
				start_time: startTime,
				start_date: day,
			},
		}
		fetchLoadRegularMeetingRoom(param)
			.then((res) => {
				if (res.success && res.data) {
					successFn(res.data)
				} else {
					m.hide()
				}
			})
			.catch(() => {
				m.hide()
			})
	} else {
		fetchLoadMeetingRoom(data)
			.then((res) => {
				if (res.success && res.data) {
					successFn(res.data)
				} else {
					m.hide()
				}
			})
			.catch(() => {
				m.hide()
			})
	}
}

/**清除已经锁定的会议室 */
export function clearLockedRooms(yesCallback: () => void, noCallBack: () => void, msg: React.ReactNode) {
	checkExistLocked((data) => {
		if (data) {
			//存在锁定会议
			confirmModal({
				msg: msg,
				onOk: () => {
					unLockMeetingRoom(() => {
						removeRoomData()
						yesCallback()
					})
				},
				onCancel: () => {
					noCallBack()
				},
			})
		} else {
			yesCallback()
		}
	})
}
/** 是否存在锁定会议室 */
export function checkExistLocked(cb: (val: boolean) => void) {
	let m = Message.loading(t('正在查询是否已锁定会议室，请稍候……'))
	fetchMeetingRoomLockExist({ meeting_form_key: useCreateContentStore.getState().meetingFormKey })
		.then((res) => {
			if (res.success) {
				cb(res.exist)
			} else {
				Alert(t('检测是否已锁定会议室出错'))
			}
			m.hide()
		})
		.catch(() => {
			m.hide()
		})
}
